<script setup lang="ts">
// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 模块导入 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

import { computed, reactive, ref, watch } from 'vue';
import dayjs from 'dayjs';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { fetchAddCjRecord, fetchCjRecordAuth, fetchCjRecordExtInfo, fetchUpdateCjRecord } from '@/service/api';
import { useDict } from '@/hooks/business/dict';
import { StringUtil } from '@/utils/z';
import { useAuth } from '@/hooks/business/auth';

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组件名称 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

defineOptions({
  name: 'CjRecordOperateDrawer'
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 组合式函数 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const { currentOrgPosition } = useAuth();

const { formRef, validate, restoreValidation } = useNaiveForm();

const { dictOptions, dictLabel, dictTag } = useDict();

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 父子传参 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

export type OperateType = NaiveUI.TableOperateType | 'view' | 'auth';

interface Props {
  operateType: OperateType;
  rowData?: Api.Sampling.Record | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

// const isAdd = computed(() => props.operateType === 'add');

// const isEdit = computed(() => props.operateType === 'edit');

// const isView = computed(() => props.operateType === 'view');

const isAuth = computed(() => props.operateType === 'auth');

// const title = computed(() => {
//   const titles: Record<OperateType, string> = {
//     add: $t('common.add'),
//     edit: $t('common.edit'),
//     view: $t('common.view'),
//     auth: '审核'
//   };
//   return titles[props.operateType];
// });

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务模型 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

const extInfo = ref<Api.Sampling.CjRecord.ExtInfo>(createExtInfo());

function createExtInfo(): Api.Sampling.CjRecord.ExtInfo {
  return {
    members: {},
    eastImage: '',
    southImage: '',
    westImage: '',
    northImage: '',
    centerGps: '',
    waterSourceImage: '',
    disasterImage: '',
    otherImage: '',
    soilSamplingSceneImage: '',
    soilSamplePackageImage: '',
    soilBag2Label2Image: '',
    soilOtherImage: '',
    cropSamplingSceneImage: '',
    cropSamplePackageImage: '',
    cropBag2Label2Image: '',
    cropOtherImage: '',
    auditRecords: []
  };
}

const opinion = ref<string>('');

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

function handleInitModel() {
  opinion.value = '';
  if (['view', 'auth'].includes(props.operateType) && props.rowData) {
    initExtInfo();
  }
}

function closeDrawer() {
  visible.value = false;
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务方法 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

async function initExtInfo() {
  if (props.rowData) {
    const { error, data } = await fetchCjRecordExtInfo(props.rowData.id, props.rowData.orgId);
    if (!error && data) {
      extInfo.value = data;
    }
  }
}

async function handleAuth(taskStatus: string, auditType: string) {
  const authData: Api.Sampling.CjRecord.AuthModel = {
    taskId: props.rowData!.taskId,
    recordId: props.rowData!.id,
    auditType,
    opinion: opinion.value,
    taskStatus
  };
  const { error, data } = await fetchCjRecordAuth(authData);
  if (!error && data) {
    window.$message?.success('操作成功');
    closeDrawer();
    emit('submitted');
  } else {
    window.$message?.success('操作失败');
  }
}

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 框架生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

// +++++++++++++++++++++++++++++++++++++++++++++++
// ---------- 业务生命周期 ----------
// +++++++++++++++++++++++++++++++++++++++++++++++
</script>

<template>
  <NModal
    v-model:show="visible"
    title="样品采集现场记录表"
    preset="card"
    class="record-modal w-1280px bg-#f4f4f4"
    :close-on-esc="false"
    :mask-closable="false"
  >
    <div id="record-info">
      <div class="record-info-print hidden">
        <NButton strong secondary>
          <template #icon>
            <icon-carbon:printer class="text-icon" />
          </template>
        </NButton>
      </div>
    </div>
    <div class="record-info-subject top">
      <div class="record-info-subject-title">一、工作信息</div>
      <div class="record-info-subject-content">
        <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="label-180">采样小组：</td>
              <td class="content-423">{{ props.rowData?.orgName }}</td>
              <td class="label-180">采样时间：</td>
              <td class="content-423">{{ dayjs(props.rowData?.samplingTime).format('YYYY-MM-DD HH:mm:ss') }}</td>
            </tr>
            <tr>
              <td>组长：</td>
              <td>{{ StringUtil.join(extInfo.members['组长'], ',') }}</td>
              <td>组员：</td>
              <td>{{ StringUtil.join(extInfo.members['组员'], ',') }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="record-info-subject">
      <div class="record-info-subject-title">二、点位基本信息</div>
      <div class="record-info-subject-content">
        <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="label-180">点位编码：</td>
              <td class="content-423">{{ props.rowData?.code }}</td>
              <td class="label-180">点位类型：</td>
              <td class="content-423">{{ dictLabel('cj_position_type', props.rowData?.positionType || '') }}</td>
            </tr>
            <tr>
              <td>点位地址：</td>
              <td colspan="3">
                {{
                  `${props.rowData?.provinceName || ''}${props.rowData?.cityName || ''}${props.rowData?.countyName || ''}${props.rowData?.town || ''}${props.rowData?.village || ''}${props.rowData?.team || ''}`
                }}
              </td>
            </tr>
            <tr>
              <td>经度：</td>
              <td>{{ props.rowData?.wgs84Longitude }}</td>
              <td>纬度：</td>
              <td>{{ props.rowData?.wgs84Latitude }}</td>
            </tr>
            <tr>
              <td>海拔：</td>
              <td colspan="3">{{ props.rowData?.wgs84Altitude }}</td>
            </tr>
            <tr>
              <td>屏显经度：</td>
              <td>{{ props.rowData?.screenLongitude }}</td>
              <td>屏显纬度：</td>
              <td>{{ props.rowData?.screenLatitude }}</td>
            </tr>
            <tr>
              <td>屏显海拔：</td>
              <td colspan="3">{{ props.rowData?.screenAltitude }}</td>
            </tr>
            <tr>
              <td>土地利用方式：</td>
              <td>{{ dictLabel('cj_land_use', props.rowData?.landUse || '') }}</td>
              <td>土壤类型：</td>
              <td>{{ dictLabel('cj_soil_type', props.rowData?.soilType || '') }}</td>
            </tr>
            <tr>
              <td>保护策略：</td>
              <td colspan="3">{{ dictLabel('cj_protection_strategy', props.rowData?.protectionStrategy || '') }}</td>
            </tr>
            <tr>
              <td>主产农作物：</td>
              <td>{{ dictLabel('cj_main_crop', props.rowData?.mainCrop || '') }}</td>
              <td>作物类别：</td>
              <td>{{ dictLabel('cj_crop_type', props.rowData?.cropType || '') }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="record-info-subject">
      <div class="record-info-subject-title">三、采样田块信息调查</div>
      <div class="record-info-subject-content">
        <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td rowspan="2" class="w-25%">施肥量（千克/年/亩）：</td>
              <td class="w-25%">氮：{{ props.rowData?.nitrogen }}</td>
              <td class="w-25%">磷：{{ props.rowData?.phosphate }}</td>
              <td class="w-25%">钾：{{ props.rowData?.potassium }}</td>
            </tr>
            <tr>
              <td>有机肥：{{ props.rowData?.organic }}</td>
              <td colspan="2">复合肥：{{ props.rowData?.compound }}</td>
            </tr>
            <tr>
              <td rowspan="3">农药施用情况（只填品名）：</td>
              <td colspan="3">杀菌剂：</td>
            </tr>
            <tr>
              <td colspan="3">杀虫剂：</td>
            </tr>
            <tr>
              <td colspan="3">除草剂：</td>
            </tr>
            <tr>
              <td>正东：{{ props.rowData?.eastInfo }}</td>
              <td>正南：{{ props.rowData?.southInfo }}</td>
              <td>正西：{{ props.rowData?.westInfo }}</td>
              <td>正北：{{ props.rowData?.northInfo }}</td>
            </tr>
            <tr>
              <td colspan="4" class="bg-#f4f4f4 pb-2px pl-3px pr-3px pt-2px">
                <table class="w-100%" border="0" cellpadding="0" cellspacing="0">
                  <tbody>
                    <tr>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.eastImage)" :src="extInfo.eastImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.southImage)" :src="extInfo.southImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.westImage)" :src="extInfo.westImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.northImage)" :src="extInfo.northImage" class="w-100%" />
                      </td>
                    </tr>
                    <tr>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.centerGps)" :src="extInfo.centerGps" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.waterSourceImage)" :src="extInfo.waterSourceImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.disasterImage)" :src="extInfo.disasterImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.otherImage)" :src="extInfo.otherImage" class="w-100%" />
                      </td>
                    </tr>
                  </tbody>
                </table>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="record-info-subject">
      <div class="record-info-subject-title">四、土壤样品信息</div>
      <div class="record-info-subject-content">
        <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="w-25%">实际采样点位置</td>
              <td class="w-25%">屏显经度：{{ props.rowData?.screenLongitude }}</td>
              <td class="w-25%">屏显纬度：{{ props.rowData?.screenLatitude }}</td>
              <td class="w-25%">屏显海拔（m）：{{ props.rowData?.screenAltitude }}</td>
            </tr>
            <tr>
              <td colspan="4">土壤样品编码：{{ props.rowData?.soilSamplingCode }}</td>
            </tr>
            <tr>
              <td>采样现场（带工具）：</td>
              <td>样品包装（袋或瓶）</td>
              <td>重量（1.5千克）</td>
              <td>样品编码</td>
            </tr>
            <tr>
              <td colspan="4" class="bg-#f4f4f4 pb-2px pl-3px pr-3px pt-2px">
                <table class="w-100%" border="0" cellpadding="0" cellspacing="0">
                  <tbody>
                    <tr>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.soilSamplingSceneImage)" :src="extInfo.soilSamplingSceneImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.soilSamplePackageImage)" :src="extInfo.soilSamplePackageImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-show="StringUtil.isNotEmpty(extInfo.soilBag2Label2Image)" :src="extInfo.soilBag2Label2Image" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-if="StringUtil.isNotEmpty(extInfo.soilOtherImage)" :src="extInfo.soilOtherImage" class="w-100%" />
                      </td>
                    </tr>
                  </tbody>
                </table>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="record-info-subject">
      <div class="record-info-subject-title">五、农产品样品信息</div>
      <div class="record-info-subject-content">
        <table border="0" cellpadding="0" cellspacing="0">
          <tbody>
            <tr>
              <td class="w-25%">实际采样点位置</td>
              <td class="w-25%">屏显经度：{{ props.rowData?.screenLongitude }}</td>
              <td class="w-25%">屏显纬度：{{ props.rowData?.screenLatitude }}</td>
              <td class="w-25%">屏显海拔（m）：{{ props.rowData?.screenAltitude }}</td>
            </tr>
            <tr>
              <td colspan="1">农产品样品编码：{{ props.rowData?.cropSamplingCode }}</td>
              <td colspan="1">主产农作物：{{ dictLabel('cj_main_crop', props.rowData?.mainCrop || '') }}</td>
              <td colspan="2">作物类型：{{ dictLabel('cj_crop_type', props.rowData?.cropType || '') }}</td>
            </tr>
            <tr>
              <td colspan="2">农产品名称：{{ props.rowData?.cropName }}</td>
              <td colspan="2">农产品样品重量：{{ props.rowData?.cropWeight }}KG</td>
            </tr>
            <tr>
              <td colspan="4">当季产量（公斤/亩）：{{ props.rowData?.quarterProduction }}</td>
            </tr>
            <tr>
              <td>采样现场（带工具）：</td>
              <td>样品包装：</td>
              <td>双袋双标签：</td>
              <td>样品编码：</td>
            </tr>
            <tr>
              <td colspan="4" class="bg-#f4f4f4 pb-2px pl-3px pr-3px pt-2px">
                <table class="w-100%" border="0" cellpadding="0" cellspacing="0">
                  <tbody>
                    <tr>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-if="StringUtil.isNotEmpty(extInfo.cropSamplingSceneImage)" :src="extInfo.cropSamplingSceneImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-if="StringUtil.isNotEmpty(extInfo.cropSamplePackageImage)" :src="extInfo.cropSamplePackageImage" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-if="StringUtil.isNotEmpty(extInfo.cropBag2Label2Image)" :src="extInfo.cropBag2Label2Image" class="w-100%" />
                      </td>
                      <td class="w-25% bg-#f4f4f4 p-2px">
                        <img v-if="StringUtil.isNotEmpty(extInfo.cropOtherImage)" :src="extInfo.cropOtherImage" class="w-100%" />
                      </td>
                    </tr>
                  </tbody>
                </table>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div class="record-info-subject">
      <div class="record-info-subject-title">审核信息</div>
      <div class="record-info-subject-content">
        <table border="0" cellpadding="0" cellspacing="0">
          <thead>
            <tr>
              <td class="w-13%">时间</td>
              <td class="w-8%">操作人</td>
              <td class="w-12%">操作人部门</td>
              <td class="w-7%">审核类型</td>
              <td class="w-11%">采样任务状态</td>
              <td class="w-49%">审批意见</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in extInfo.auditRecords" :key="item.id">
              <td>{{ dayjs(item.auditTime).format('YYYY-MM-DD HH:mm:ss') }}</td>
              <td>{{ item.createUser }}</td>
              <td>{{ item.orgName }}</td>
              <td>{{ dictLabel('cj_audit_type', item.auditType) }}</td>
              <td>{{ dictLabel('cj_task_status', item.taskStatus) }}</td>
              <td>{{ item.opinion }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <div :class="`record-info-subject ${isAuth ? '' : 'hidden'}`">
      <div class="record-info-subject-title">审批意见 (当前状态：{{ dictLabel('cj_task_status', props.rowData?.taskStatus || '') }})</div>
      <div
        v-if="
          (currentOrgPosition()?.positionName === '组长' && props.rowData?.taskStatus === '3') ||
          (currentOrgPosition()?.positionName === '省组长' && (props.rowData?.taskStatus === '4' || props.rowData?.taskStatus === '6'))
        "
        class="record-info-subject-content mt-12px"
      >
        <NInput v-model:value="opinion" type="textarea" />
      </div>
      <div class="auth-btn mt-8px flex justify-center pb-16px">
        <template v-if="currentOrgPosition()?.positionName === '组长' && props.rowData?.taskStatus === '3'">
          <NButton type="success" class="ml-12px" @click="handleAuth('4', '3')">
            <template #icon>
              <icon-material-symbols:check class="text-icon" />
            </template>
            小组审核通过
          </NButton>
          <NButton type="success" class="ml-12px" @click="handleAuth('5', '4')">
            <template #icon>
              <icon-material-symbols:check class="text-icon" />
            </template>
            小组审核不通过
          </NButton>
        </template>
        <template v-if="currentOrgPosition()?.positionName === '省组长' && (props.rowData?.taskStatus === '4' || props.rowData?.taskStatus === '6')">
          <NButton type="success" class="ml-12px" @click="handleAuth('6', '3')">
            <template #icon>
              <icon-material-symbols:check class="text-icon" />
            </template>
            平台审核通过
          </NButton>
          <NButton type="error" class="ml-12px" @click="handleAuth('7', '4')">
            <template #icon>
              <icon-material-symbols:close class="text-icon" />
            </template>
            平台审核不通过
          </NButton>
        </template>
      </div>
    </div>
    <template #footer>
      <NSpace justify="end" class="pt-10px">
        <NButton type="error" @click="closeDrawer">关闭</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style lang="scss">
.record-modal {
  .n-card__content {
    background-color: #f4f4f4;
  }

  .btw-0 {
    border-bottom-width: 0px;
  }

  .record-info-print {
    margin-bottom: 2px;
  }

  .record-info-subject {
    background-color: #fff;
    margin-top: 10px;
    border-radius: 4px;
    color: #595959;
    font-size: 13px;

    &.top {
      margin-top: 0;
    }

    .record-info-subject-title {
      border-bottom: 1px solid #e7eaec;
      font-weight: bold;
      padding: 0 15px;
      line-height: 36px;
      font-size: 14px;
    }

    .record-info-subject-content {
      padding: 0 25px 12px 25px;

      > table {
        width: 100%;

        > thead {
          font-weight: bold;
        }

        > thead,
        > tbody {
          > tr {
            border-bottom: 1px solid #eaecee;

            > td {
              line-height: 36px;

              &.label-180 {
                width: 180px;
              }

              &.content-423 {
                width: 423px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
